package com.larly.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.larly.exception.ErrorCode;
import com.larly.exception.ThrowUtils;
import com.larly.model.domain.NoteShares;
import com.larly.model.domain.Notes;
import com.larly.model.domain.User;
import com.larly.model.dto.noteshare.ShareNotesRequest;
import com.larly.model.enums.notes.NotesIsPublic;
import com.larly.model.vo.NotesVO;
import com.larly.model.vo.UserVO;
import com.larly.service.NoteSharesService;
import com.larly.mapper.NoteSharesMapper;
import com.larly.service.NotesService;
import com.larly.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

/**
* @author 许颢达
* @description 针对表【note_shares(笔记分享记录表)】的数据库操作Service实现
* @createDate 2025-09-01 12:48:47
*/
@Service
public class NoteSharesServiceImpl extends ServiceImpl<NoteSharesMapper, NoteShares>
    implements NoteSharesService{

    @Resource
    private UserService userService;

    @Resource
    private NotesService notesService;

    @Override
    public String shareNote(ShareNotesRequest shareNotesRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(ObjUtil.isNull(shareNotesRequest), ErrorCode.PARAM_ERROR);
        ThrowUtils.throwIf(ObjUtil.isNull(shareNotesRequest.getNoteId()), ErrorCode.PARAM_ERROR, "笔记ID不能为空");

        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        Integer noteId = shareNotesRequest.getNoteId();

        // 检查笔记是否存在且属于当前用户
        Notes note = notesService.getById(noteId);
        ThrowUtils.throwIf(ObjUtil.isNull(note), ErrorCode.RESOURCE_NOT_FOUND, "笔记不存在");
        ThrowUtils.throwIf(!note.getUserId().equals(loginUser.getId()), ErrorCode.NO_PERMISSION, "无权限操作");

        // 检查笔记是否为公开状态
        ThrowUtils.throwIf(note.getIsPublic() != NotesIsPublic.PUBLIC.getKey(), ErrorCode.OPERATION_DENIED, "只能分享公开笔记");

        // 检查是否已经分享过
        NoteShares existingShare = this.lambdaQuery()
                .eq(NoteShares::getNoteId, noteId)
                .eq(NoteShares::getUserId, loginUser.getId())
                .one();

        // 如果已经分享过，直接返回分享链接
        if (existingShare != null) {
            // 更新过期时间
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MINUTE, 5); // 5分钟后过期

            this.lambdaUpdate()
                    .eq(NoteShares::getId, existingShare.getId())
                    .set(NoteShares::getExpireTime, calendar.getTime())
                    .update();

            return existingShare.getShareLink();
        }

        // 创建公开分享记录
        NoteShares noteShare = new NoteShares();
        noteShare.setNoteId(noteId);
        noteShare.setUserId(loginUser.getId());
        String shareLink = UUID.randomUUID().toString().replace("-", "");
        noteShare.setShareLink(shareLink);
        noteShare.setCreateTime(new Date());

        // 设置过期时间为5分钟后
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        noteShare.setExpireTime(calendar.getTime());

        boolean saved = this.save(noteShare);
        ThrowUtils.throwIf(!saved, ErrorCode.SYSTEM_ERROR, "分享失败");

        return shareLink;
    }

    @Override
    public NotesVO getNoteByShareLink(String shareLink) {
        ThrowUtils.throwIf(ObjUtil.isEmpty(shareLink), ErrorCode.PARAM_ERROR, "分享链接不能为空");

        // 根据分享链接查找分享记录
        NoteShares noteShare = this.lambdaQuery()
                .eq(NoteShares::getShareLink, shareLink)
                .one();

        ThrowUtils.throwIf(ObjUtil.isNull(noteShare), ErrorCode.RESOURCE_NOT_FOUND, "分享链接无效或已取消");

        // 检查是否过期（惰性删除）
        if (noteShare.getExpireTime() != null && noteShare.getExpireTime().before(new Date())) {
            // 删除过期记录
            this.removeById(noteShare.getId());
            ThrowUtils.throwIf(true, ErrorCode.OPERATION_DENIED, "分享链接已过期");
        }

        // 获取笔记信息
        Notes note = notesService.getById(noteShare.getNoteId());
        ThrowUtils.throwIf(ObjUtil.isNull(note), ErrorCode.RESOURCE_NOT_FOUND, "笔记不存在");

        NotesVO notesVo = NotesVO.toVO(note);
        User user = userService.getById(note.getUserId());
        if (user != null) {
            notesVo.setUserVO(UserVO.toVO(user));
        }

        return notesVo;    }
}




